import React, { useEffect, useState } from 'react'
import { Popup, PickerView } from 'antd-mobile'
import type { CityListType } from '../../../api/interface'
import styles from '../../index.module.less'

interface Props {
    visible: boolean
    setVisible: (v: boolean) => void
    onChange?: (v: unknown) => void
    value: [string, string]
    provinceList: CityListType[]
    cityMap: Record<string, CityListType[]>
}
type SelectType = {
    label: string
    value: string
    children: CityListType[]
}

type DataSourceType = [SelectType[], SelectType[]]
let lastProvinceId: string = ''
export default (props: Props) => {
    const { visible, setVisible, onChange, provinceList, cityMap } = props
    const [value, setValue] = useState<[string, string]>(props.value)

    const formatterData = (list: CityListType[] = []): SelectType[] => {
        return list.map(v => ({
            label: v.name,
            value: v.code,
            children: v.children,
        }))
    }

    const [dataSource, setDataSource] = useState<DataSourceType>([[], []])

    useEffect(() => {
        const provinceCode = value[0]
        if (provinceList) {
            let defaultData: DataSourceType = [formatterData(provinceList), []]
            if (provinceCode) {
                defaultData[1] = formatterData(cityMap[provinceCode])
            }
            setDataSource(defaultData)
        }
    }, [provinceList, cityMap, value])

    const onSelectChange = (val: [string, string]) => {
        const [provinceCode] = val
        if (!lastProvinceId || lastProvinceId !== provinceCode) {
            setDataSource(state => {
                let arr: DataSourceType = [...state]
                arr[1] = formatterData(cityMap[provinceCode])
                return arr
            })
        }
        setValue(val)
    }

    const onSubmit = () => {
        onChange && onChange(value)
        setVisible(false)
    }

    return (
        <Popup
            visible={visible}
            onMaskClick={() => {
                setVisible(false)
            }}
            bodyStyle={{ height: '30vh' }}
        >
            <div>
                <div className={styles.handleBar}>
                    <div onClick={() => setVisible(false)}>取消</div>
                    <div onClick={onSubmit}>确认</div>
                </div>
                <PickerView columns={dataSource} value={value} onChange={onSelectChange} />
            </div>
        </Popup>
    )
}
